# 协程 单线程下的开发
import time
from greenlet import greenlet
import gevent
from gevent import monkey


def task1():
    while True:
        yield '哈哈哈'
        time.sleep(1)


def task2():
    while True:
        yield '嘿嘿嘿'
        time.sleep(1)


# if __name__ == '__main__':
#     t1 = task1()
#     t2 = task2()
#     while True:
#         print(next(t2))
#         print(next(t1))

# greenlet 协程模块 手动切换
# def sing():
#     print("在唱歌")
#     g2.switch()
#     print("唱完歌")
#
#
# def dance():
#     print("在跳舞")
#     print("跳完舞")
#     g1.switch()


# if __name__ == '__main__':
#     # 创建协程对象
#     g1 = greenlet(sing)
#     g2 = greenlet(dance)
#     g1.switch()
#     g2.switch()

# gevent 遇到 IO操作时，会自动切换
# 创建协程对象
# gevent.spawn('task1')
# 耗时操作
# gevent.sleep(2)
# 等待所有协程对象执行结束
# gevent.joinall()
# 等待某个协程结束
# gevent.join()

# def sing():
#     print("在唱歌")
#     gevent.sleep(2)
#     print("唱完歌")
#
#
# def dance():
#     print("在跳舞")
#     gevent.sleep(3)
#     print("跳完舞")
#
#
# if __name__ == '__main__':
#     # 创建协程对象
#     g1 = gevent.spawn(sing)
#     g2 = gevent.spawn(dance)
#     g1.join()
#     g2.join()

# joinall 等待所有协程执行完成
# def sing(name):
#     for i in range(3):
#         gevent.sleep(3)
#         print(f"{name}在唱歌，被送走了第{i}次")
#
#
# if __name__ == '__main__':
#     gevent.joinall([
#         gevent.spawn(sing, "张三"),
#         gevent.spawn(sing, "李四")
#     ])

# monket 补丁
monkey.patch_all()


def sing(name):
    for i in range(3):
        time.sleep(1)
        print(f"{name}在唱歌，被送走了第{i}次")


if __name__ == '__main__':
    gevent.joinall([
        gevent.spawn(sing, "张三"),
        gevent.spawn(sing, "李四")
    ])
